//
//  JYSearchViewController.m
//  JYFarm
//
//  Created by 花花 on 2017/10/10.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYSearchViewController.h"
#import "JYSearchBar.h"
#import "JYSearchHistoryView.h"
#import "JYSearchHistoryCell.h"
#import "JYSearchHistoryManager.h"
#import "JYPublicCell.h"
#import "JYEmptyView.h"
#import "JYHomeViewModel.h"
@interface JYSearchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,JYHomeViewModelDelegate>
@property(nonatomic) UIView *navBarView;
@property(nonatomic) JYSearchBar *searchBar;

@property(nonatomic) UIButton *searchButton; //搜索按钮

@property(nonatomic) UIButton *backBtn; //返回按钮

@property(nonatomic)JYSearchHistoryView *searchHistoryView; //历史记录

@property(nonatomic)UICollectionView *collectionView; //collectionView

@property(nonatomic)NSString *searchName; //搜索的name值

@property(nonatomic)NSMutableArray *searchListData; //搜索列表

@property(nonatomic,assign)NSInteger count; //保存数量

@property(nonatomic)JYHomeViewModel *viewModel;

@end

static NSString *const SearchListCellID = @"SearchListCellID";
static NSString *const SearchHistoryCellID = @"SearchHistoryCellID";
@implementation JYSearchViewController

- (JYHomeViewModel *)viewModel{

    if (!_viewModel) {
        _viewModel = [[JYHomeViewModel alloc]init];
        _viewModel.delegate = self;
    }

    return _viewModel;
}
#pragma mark - <JYHomeViewModelDelegate>
//获取数据
- (void)homeRightTableRequestDataSuccessWithArray:(NSMutableArray *)dataArray{

    self.searchListData = dataArray;

    [self.tableView reloadData];
}
- (void)shopcartAccountFortotalCount:(double)totalCount{

    [self.tableView reloadData];
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHistory) name:kSaveHistoryItemSuccessNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupNav];
    [self initConstraint];
    [self.view addSubview:self.searchHistoryView];
    [self.view addSubview:self.collectionView];
    
    
//    [self loadDataFromNetwork];
}

#pragma mark - refreshHistory
- (void)refreshHistory{

//    self.dataArr = [[JYSearchHistoryManager shareInstance] getSearchHistoryArray];
    
    [self.collectionView reloadData];
    
    self.searchHistoryView.noHistoryLablel.hidden = self.dataArr.count>0?YES:NO;
}

#pragma mark - searchList
- (void)searchList{
    
    
    [self.searchHistoryView removeFromSuperview];
    [self.collectionView removeFromSuperview];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - setupNav
- (void)setupNav{
    self.navBarView = [[UIView alloc] init];
    self.navBarView.backgroundColor = kfColor;
    [self.view addSubview:self.navBarView];
    
    self.searchBar = [[JYSearchBar alloc]initWithOffSet:40];
    self.searchBar.searchEnable = true;
    [self.searchBar.textFiled becomeFirstResponder];
    self.searchBar.textFiled.text = nil;

    [self.navBarView addSubview:self.searchBar];
    JYWeakSelf;
    self.searchBar.searchBarInputCallBack = ^(NSString *inputString){
        weakSelf.searchName = inputString;
        
    };
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
    self.backBtn.imageEdgeInsets = UIEdgeInsetsMake(20, -10, 0, 0);
    [self.navBarView addSubview:self.backBtn];
    [self.backBtn addTarget:self action:@selector(backOnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchButton = [[UIButton alloc] init];
    [self.searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    
    [self.searchButton setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
    self.searchButton.titleLabel.font = kFont(14);
    self.searchButton.titleEdgeInsets = UIEdgeInsetsMake(15, 0, 0, 0);
    [self.searchButton addTarget:self action:@selector(searchOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:self.searchButton];

}
#pragma mark - initConstraint
- (void)initConstraint{
    JYWeakSelf;
    [self.navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.height.equalTo(@64);
    }];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.top.equalTo(weakSelf.view.mas_top);
        make.width.equalTo(@60);
        make.height.equalTo(@64);
    }];
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.width.equalTo(@60);
        make.height.equalTo(@64);
    }];
    
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.navBarView.mas_left);
        make.right.equalTo(weakSelf.searchButton.mas_left).offset(15);
        make.top.equalTo(weakSelf.navBarView.mas_top);
        make.height.equalTo(@64);
    }];
}
- (void)addUserShopCartIndexPath:(NSIndexPath *)indexPath count:(NSInteger)count{
    
    
    JYSearchModel *productModel =[self.searchListData safeObjectAtIndex:indexPath.row];
    
    if (count <= 0) {
        count = 1;
    } else  if (count > 10000) {
        count = productModel.amount;
    }
    //根据请求结果决定是否改变数据
    productModel.amount = count;
    
    
    [self adduserShoppingTrolleyListIndexPath:indexPath count:count];
    
}

- (void)adduserShoppingTrolleyListIndexPath:(NSIndexPath *)indexPath count:(NSInteger)count{
    
    /**
     categroyId = 2;
     createTime = "<null>";
     deletCommonUserOrderType = 0;
     depositObj = "<null>";
     goodsAmount = 1;
     goodsDesc = "<null>";
     goodsId = 7;
     goodsName = "\U5f20\U88d5\U4e8c\U53f7";
     goodsPictureUrl = "http://pic.jinyoufarm.com/72df0411.jpg";
     goodsPrice = "1.2";
     list = "<null>";
     operateType = 0;
     originalprice = 20;
     unit = "\U4e2a";
     userId = "8f42310f-0bfc-4b79-a6f9-52b0b0adc384";
     
     
     */
    JYSearchModel *productModel =[self.searchListData safeObjectAtIndex:indexPath.row];
    
    
    NSDictionary *param = @{
                            @"list":@[@{@"goodsAmount":@(count),@"goodsId":productModel.id,@"goodsName":productModel.name,@"goodsPictureUrl":productModel.image,@"goodsPrice":productModel.price,@"originalprice":@(20),@"unit":@"个",@"userId":LH.userId,@"categroyId":@(2)
//                                        @"depositObj":@[@{@"goodsAmount":depositModel.amount,@"goodsId":depositModel.id,@"goodsName":depositModel.image,@"goodsPictureUrl":depositModel.image,@"unit":depositModel.spec,@"goodsPrice":depositModel.price
//                                                          }]
                                        }]
                            };
    
    [HTTPRequest POST:kAdduserShoppingTrolleyUrl parameter:param success:^(id resposeObject) {
        
        NSLog(@"添加商品到购物车 %@",resposeObject);
        if (SUCCESS) {
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kCountChangeNotification object:nil];
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        }
        
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
        
    }];
    
    
    
}


#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.searchListData.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    JYPublicCell *cell =[tableView dequeueReusableCellWithIdentifier:SearchListCellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BaseModel *model =  [self.searchListData safeObjectAtIndex:indexPath.row];
    cell.homeModel=  model;
    JYWeakSelf;
    cell.ShopCountEditBlock = ^(NSInteger count,UIImageView *imgeView){
        
        [weakSelf.viewModel changeCountAtIndexPath:indexPath count:count];
    
        [weakSelf GoodCarTotalCountFormNetwork];
        
        [tableView reloadData];
        

    };
    
    cell.selectStarsBtnClick = ^(BOOL isSelected){
        
          model.collect = !model.collect;
        
        if (isSelected == YES) {
            
            [weakSelf.viewModel selectProductAtIndexPath:indexPath isSelected:isSelected];

        }else{
        
            [weakSelf.viewModel cancelProductAtIndexPath:indexPath];
        }
   
    };

    return cell;
}
- (void)loadgoodsListCategoryId:(NSString *)categoryId{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];

    param[@"userId"] = LH.userId;
    param[@"categoryId"] = categoryId;
    [HTTPRequest POST:kFrontGoodsUrl parameter:param success:^(id resposeObject) {
        
        if (SUCCESS) {
            
            [self.searchListData removeAllObjects];
            
            self.searchListData = [BaseModel mj_objectArrayWithKeyValuesArray:resposeObject[@"data"][@"list"]];
            
            [self.viewModel requsetHomeRithtTableList:self.searchListData];
            [self.tableView reloadData];
            
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        }
        
        NSLog(@"_____右边数据右边数据______%@",resposeObject);
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
        
    }];
    
}


- (void)GoodCarTotalCountFormNetwork{
    
    
    [HTTPRequest POST:kUserShoppingTrolleyGoodsTotalUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {
        JYWeakSelf;
        if (SUCCESS) {
            int totalCount = [resposeObject[@"data"] intValue];
            
            NSLog(@"购物车数量: %d",totalCount);
            if (totalCount>0) {
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",totalCount];
                
            }else{
                
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = nil;
            }
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
        
    } failure:^(NSError *error) {
        
        //          [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
    }];
    
    
}



#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

        JYSearchHistoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SearchHistoryCellID forIndexPath:indexPath];
        cell.model = [self.dataArr safeObjectAtIndex:indexPath.row];
        return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    JYSearchModel *model  = [self.dataArr safeObjectAtIndex:indexPath.row];
    [self queryShopListName:model.name];
}
//每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.dataArr.count==0) return CGSizeZero;
    CGFloat itemW = (Screen_Width-5*10)/4;
    
    return CGSizeMake(itemW,25);
}
//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0,10,10,10);

}

//设置每个item的水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10;
}
#pragma mark - SEL Methods
- (void)backOnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchOnClick{
    
    if (self.searchName.length !=0 ) {
        JYSearchModel *model = [JYSearchModel initWithName:self.searchName];
        
        [[JYSearchHistoryManager shareInstance] saveSearchItemToHistory:model];
        
        [self.dataArr addObject:model];
    }
    [self queryShopListName:self.searchName];
}

#pragma mark - loadData
- (void)queryShopListName:(NSString *)keywords{
    
    NSLog(@"keywords:%@",keywords);
    if (keywords.length == 0 || [keywords isEqualToString:@""]) return;
    
    NSDictionary *param = @{@"keywords":keywords,
                            @"userId":LH.userId,
                            @"pageNo":@1,
                            @"pageSize":@20
                            };
    JYWeakSelf;

    
    
    [HTTPRequest POST:kFrontGoodsUrl parameter:param success:^(id resposeObject) {
       
        NSLog(@"搜索列表%@",resposeObject);
        if (SUCCESS) {
            
            [self.searchListData removeAllObjects];
            NSArray *listArr = resposeObject[@"data"][@"list"];
            if (listArr.count>0) {
                [JYEmptyView hiddenEmptyInView:weakSelf.tableView];
                weakSelf.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                weakSelf.searchListData = [JYSearchModel mj_objectArrayWithKeyValuesArray:listArr];
                
                for (NSDictionary *dic in resposeObject[@"data"][@"list"]) {
                    
                    self.viewModel.depositObjDic = dic[@"depositObj"];
                }
                
                [weakSelf.viewModel requsetHomeRithtTableList:weakSelf.searchListData];
            }else{
                
                weakSelf.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
                [JYEmptyView showEmptyInView:weakSelf.tableView WithMessage:@"暂无该商品"];
            }
            
            [self.tableView reloadData];
            [self.collectionView reloadData];
            [self searchList];
        }else{
        
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
    } failure:^(NSError *error) {
        
       [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
    }];
}


#pragma #pragma mark - Setter && Getter Methods
- (NSMutableArray *)dataArr{
    
    if (_dataArr == nil) {
        _dataArr = [[JYSearchHistoryManager shareInstance]getSearchHistoryArray];
        //缓存为空则初始化
        if (_dataArr == nil) {
            
            _dataArr = [NSMutableArray array];
        }
    }
    return _dataArr;
}
- (UICollectionView *)collectionView{

    if (!_collectionView) {
        UICollectionViewFlowLayout *layot = [[UICollectionViewFlowLayout alloc]init];
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchHistoryView.frame), Screen_Width,100) collectionViewLayout:layot];
        [_collectionView registerClass:[JYSearchHistoryCell class] forCellWithReuseIdentifier:SearchHistoryCellID];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;

}
- (JYSearchHistoryView *)searchHistoryView{

    if (!_searchHistoryView) {
      
        _searchHistoryView = [[JYSearchHistoryView alloc]init];
        _searchHistoryView.noHistoryLablel.hidden = (self.dataArr.count>0?YES:NO);
        _searchHistoryView.frame = CGRectMake(0, 65, Screen_Width, 40);
        _searchHistoryView.backgroundColor =[UIColor whiteColor];
        JYWeakSelf;
        
        [_searchHistoryView setEmptySearchHistoryOnClick:^{
            NSLog(@"清空数据");
            [[JYSearchHistoryManager shareInstance]clearAllSearchHistory];
            weakSelf.searchHistoryView.height = 40;
            weakSelf.searchHistoryView.noHistoryLablel.hidden = NO;
            [weakSelf.collectionView reloadData];
       
        }];
    }
    return _searchHistoryView;
}
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView =  [[UITableView alloc] initWithFrame:CGRectMake(0, 65, Screen_Width,Screen_Height-65)];
        _tableView.backgroundColor = kBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.tableView registerNib:[UINib nibWithNibName:@"JYPublicCell" bundle:nil] forCellReuseIdentifier:SearchListCellID];
        self.tableView.rowHeight = 100;
        
    }
    return _tableView;
    
}
- (NSMutableArray *)searchListData{
    
    if (!_searchListData) {
        _searchListData = [NSMutableArray array];
    }
    return _searchListData;
    
}

@end
